<template>
  <div class="home">
    <SideNav />
    <div class="main-content">
      <!-- 顶部数据卡片 -->
      <div class="stat-cards">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-code"></i>
          </div>
          <div class="stat-info">
            <h3>今日解题</h3>
            <div class="stat-value">{{ todaySolved }}</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-check-circle"></i>
          </div>
          <div class="stat-info">
            <h3>总题数</h3>
            <div class="stat-value">{{ totalProblems }}</div>
          </div>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="content-grid">
        <!-- 系统公告 -->
        <div class="panel announcements-panel">
          <div class="panel-header">
            <h2>系统公告</h2>
          </div>
          <div class="announcements-container">
            <div class="announcements-scroll">
              <div v-for="announcement in announcements" 
                   :key="announcement.id" 
                   class="announcement-item">
                <div class="announcement-header">
                  <span class="announcement-tag" :class="announcement.type">
                    {{ getAnnouncementTypeText(announcement.type) }}
                  </span>
                  <span class="announcement-time">{{ announcement.time }}</span>
                </div>
                <div class="announcement-content">{{ announcement.content }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 最近活动 -->
        <div class="panel">
          <div class="panel-header">
            <h2>最近活动</h2>
          </div>
          <div v-if="loading.activities" class="loading-text">
            加载中...
          </div>
          <div v-else-if="recentActivities.length === 0" class="empty-text">
            暂无活动数据
          </div>
          <div v-else class="activity-list">
            <div v-for="activity in recentActivities" 
                 :key="activity.id" 
                 class="activity-item">
              <div class="activity-icon" :class="activity.type">
                <i :class="getActivityIcon(activity.type)"></i>
              </div>
              <div class="activity-content">
                <div class="activity-text">{{ activity.content }}</div>
                <div class="activity-time">{{ activity.time }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SideNav from '@/components/SideNav.vue'
import axios from 'axios'
import { baseURL } from '@/utils/api'
import { announcementApi } from '@/utils/api'
import { activityApi } from '@/utils/api'

export default {
  name: 'HomeView',
  components: {
    SideNav
  },
  data() {
    return {
      totalProblems: 0,
      todaySolved: 0,
      announcements: [],
      recentActivities: [],
      loading: {
        activities: false
      }
    }
  },
  methods: {
    getAnnouncementTypeText(type) {
      const types = {
        system: '系统',
        activity: '活动',
        maintenance: '维护',
        important: '重要',
        normal: '通知',
        update: '更新'
      }
      return types[type] || '通知'
    },
    getActivityIcon(type) {
      const icons = {
        solve: 'fas fa-check-circle',
        join: 'fas fa-user-plus',
        comment: 'fas fa-comment',
        task: 'fas fa-tasks',
        create: 'fas fa-plus-circle'
      }
      return icons[type] || 'fas fa-circle'
    },
    // 获取题目统计信息
    async fetchProblemStats() {
      try {
        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getProblemStats`
        });

        if (response.data.result === 'success') {
          // 更新总题目数
          this.totalProblems = response.data.totalCount;
        } else {
          console.error('获取题目统计信息失败：', response.data.message);
        }
      } catch (error) {
        console.error('获取题目统计信息失败:', error);
      }
    },
    
    // 计算今日解题数
    calculateTodaySolved() {
      // 这里可以实现计算今日解题数的逻辑
      // 由于我们没有相关API，这里仅做示例
      this.todaySolved = 5; // 静态数据，实际应该从API获取
    },
    
    // 获取公告列表
    async fetchAnnouncements() {
      try {
        console.log('正在获取公告列表...');
        const response = await announcementApi.getRecentAnnouncements(5);
        
        if (response.result === 'success') {
          console.log('获取公告成功:', response);
          
          if (response.data && response.data.announcements) {
            // 将后端数据映射到前端需要的格式
            this.announcements = response.data.announcements.map(item => {
              // 计算时间差
              const createdTime = new Date(item.created_at);
              const now = new Date();
              const timeDiff = this.formatTimeDiff(now - createdTime);
              
              return {
                id: item.id,
                type: item.type || 'normal',
                content: item.title + (item.content ? `: ${item.content}` : ''),
                time: timeDiff
              };
            });
          } else {
            console.warn('公告数据格式不符合预期:', response);
            this.announcements = [];
          }
        } else {
          console.error('获取公告列表失败:', response.message);
          // 保持默认空数组
        }
      } catch (error) {
        console.error('获取公告列表出错:', error);
      }
    },
    
    // 获取最新活动
    async fetchRecentActivities() {
      try {
        this.loading.activities = true;
        console.log('正在获取最新活动...');
        
        // 获取用户ID
        const userId = localStorage.getItem('userId');
        let response;
        
        if (userId) {
          // 如果用户已登录，获取该用户的活动
          response = await activityApi.getUserActivities(userId, 5);
        } else {
          // 否则获取全局活动
          response = await activityApi.getRecentActivities(5);
        }
        
        if (response.result === 'success') {
          console.log('获取活动成功:', response);
          
          if (response.activities && response.activities.length > 0) {
            // 将后端数据映射到前端需要的格式
            this.recentActivities = response.activities.map(item => {
              return {
                id: item.id || Math.random().toString(36).substr(2, 9),
                type: item.activityType || 'solve',
                content: item.content,
                time: item.timeFormatted
              };
            });
          } else {
            console.log('没有找到活动，使用默认数据');
            // 使用默认数据
            this.recentActivities = [
              {
                id: 1,
                type: 'solve',
                content: '解决了题目 "两数之和"',
                time: '10分钟前'
              },
              {
                id: 2,
                type: 'join',
                content: '加入了"算法进阶"小组',
                time: '2小时前'
              },
              {
                id: 3,
                type: 'comment',
                content: '在"最长回文子串"下发表了评论',
                time: '昨天'
              }
            ];
          }
        } else {
          console.error('获取活动列表失败:', response.message);
          // 使用默认数据
          this.recentActivities = [
            {
              id: 1,
              type: 'solve',
              content: '解决了题目 "两数之和"',
              time: '10分钟前'
            },
            {
              id: 2,
              type: 'join',
              content: '加入了"算法进阶"小组',
              time: '2小时前'
            },
            {
              id: 3,
              type: 'comment',
              content: '在"最长回文子串"下发表了评论',
              time: '昨天'
            }
          ];
        }
        
        this.loading.activities = false;
      } catch (error) {
        console.error('获取活动列表出错:', error);
        // 使用默认数据
        this.recentActivities = [
          {
            id: 1,
            type: 'solve',
            content: '解决了题目 "两数之和"',
            time: '10分钟前'
          },
          {
            id: 2,
            type: 'join',
            content: '加入了"算法进阶"小组',
            time: '2小时前'
          },
          {
            id: 3,
            type: 'comment',
            content: '在"最长回文子串"下发表了评论',
            time: '昨天'
          }
        ];
        this.loading.activities = false;
      }
    },
    
    // 格式化时间差
    formatTimeDiff(timeDiff) {
      const seconds = Math.floor(timeDiff / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);
      
      if (days > 0) {
        return days + '天前';
      } else if (hours > 0) {
        return hours + '小时前';
      } else if (minutes > 0) {
        return minutes + '分钟前';
      } else {
        return '刚刚';
      }
    }
  },
  async created() {
    // 获取题目统计信息
    await this.fetchProblemStats();
    
    // 计算今日解题数
    this.calculateTodaySolved();
    
    // 获取公告列表
    await this.fetchAnnouncements();
    
    // 获取最新活动
    await this.fetchRecentActivities();
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  background: #f0f7ff;
}

.main-content {
  margin-left: 60px;
  padding: 20px;
}

/* 数据卡片样式 */
.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  display: flex;
  gap: 16px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
}

.stat-card.clickable {
  cursor: pointer;
  transition: transform 0.2s;
}

.stat-card.clickable:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  background: #e8f4ff;
  color: #3498db;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-info h3 {
  color: #5b7b9a;
  font-size: 14px;
  margin-bottom: 4px;
}

.stat-value {
  color: #2c3e50;
  font-size: 24px;
  font-weight: bold;
}

.stat-subtext {
  color: #5b7b9a;
  font-size: 12px;
  margin-top: 4px;
}

/* 内容网格 */
.content-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

/* 面板样式 */
.panel {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
}

.panel-header {
  margin-bottom: 20px;
}

.panel-header h2 {
  color: #2c3e50;
  font-size: 18px;
}

/* 公告样式 */
.announcements-container {
  height: 300px;
  overflow: hidden;
}

.announcements-scroll {
  height: 100%;
  overflow-y: auto;
}

.announcement-item {
  padding: 16px;
  border-bottom: 1px solid #e8f4ff;
}

.announcement-item:last-child {
  border-bottom: none;
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.announcement-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.announcement-tag.important {
  background: #fef0f0;
  color: #f56c6c;
}

.announcement-tag.normal {
  background: #e8f4ff;
  color: #3498db;
}

.announcement-tag.update {
  background: #e8f6f1;
  color: #42b983;
}

.announcement-tag.system {
  background: #e8f4ff;
  color: #3498db;
}

.announcement-tag.activity {
  background: #e8f6f1;
  color: #42b983;
}

.announcement-tag.maintenance {
  background: #fef0f0;
  color: #f56c6c;
}

.announcement-time {
  color: #5b7b9a;
  font-size: 12px;
}

.announcement-content {
  color: #2c3e50;
  font-size: 14px;
  line-height: 1.5;
}

/* 活动列表样式 */
.activity-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.activity-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  background: #f8faff;
  border-radius: 8px;
}

.activity-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.activity-icon.solve {
  background: #e8f6f1;
  color: #42b983;
}

.activity-icon.join {
  background: #e8f4ff;
  color: #3498db;
}

.activity-icon.comment {
  background: #fdf6ec;
  color: #e6a23c;
}

.activity-content {
  flex: 1;
}

.activity-text {
  color: #2c3e50;
  font-size: 14px;
  margin-bottom: 4px;
}

.activity-time {
  color: #5b7b9a;
  font-size: 12px;
}

.loading-text {
  text-align: center;
  color: #5b7b9a;
  font-size: 14px;
}

.empty-text {
  text-align: center;
  color: #5b7b9a;
  font-size: 14px;
}
</style> 